package repository

import (
	"context"
	"time"

	"server/internal/app/model"
	"server/internal/core/store"

	"gorm.io/gorm"
)

type SysAdminLoginLogRepository struct {
	db *gorm.DB
}

func NewSysAdminLoginLogRepository() *SysAdminLoginLogRepository {
	return &SysAdminLoginLogRepository{db: store.DB}
}

func (r *SysAdminLoginLogRepository) Create(ctx context.Context, log *model.SysAdminLoginLog) error {
	return r.db.WithContext(ctx).Create(log).Error
}

func (r *SysAdminLoginLogRepository) ListByAdminID(ctx context.Context, adminID uint, limit, offset int) ([]*model.SysAdminLoginLog, error) {
	query := r.db.WithContext(ctx).
		Where("admin_id = ?", adminID).
		Order("created_at DESC")

	if limit > 0 {
		query = query.Limit(limit)
	}
	if offset > 0 {
		query = query.Offset(offset)
	}

	var logs []*model.SysAdminLoginLog
	if err := query.Find(&logs).Error; err != nil {
		return nil, err
	}
	return logs, nil
}

func (r *SysAdminLoginLogRepository) DeleteExpired(ctx context.Context, before time.Time) error {
	return r.db.WithContext(ctx).Where("expires_at < ?", before).Delete(&model.SysAdminLoginLog{}).Error
}

func (r *SysAdminLoginLogRepository) GetByToken(ctx context.Context, token string) (*model.SysAdminLoginLog, error) {
	var log model.SysAdminLoginLog
	if err := r.db.WithContext(ctx).Where("token = ?", token).First(&log).Error; err != nil {
		return nil, err
	}
	return &log, nil
}

func (r *SysAdminLoginLogRepository) DeleteByToken(ctx context.Context, token string) error {
	return r.db.WithContext(ctx).Where("token = ?", token).Delete(&model.SysAdminLoginLog{}).Error
}
